﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ODS.Config;
using ODS.Utils;
using System.IO;
using ODS.Model;
using System.Xml.Linq;
using System.Windows;

namespace ODS.WebService.DeviceData
{
    public class RetrieveDeviceLatestMessageService
    {
        static bool IsAuthenticated = true;

        public static async Task<InfoResult> RetrieveDeviceLatestMessage(String imei)
        {
            String url = Constants.SERVER_URL +"/devices/" + imei + "/messages/latest";

            InfoResult result;
            try
            {
                Stream xmlStream = await RESTfulService.HTTPGetRequest(url);

                MessageModel resultString = ParseXML(xmlStream);

                #region check authenticate
                if (!IsAuthenticated)
                {
                    InfoResult result_login = await Login_Logout.LoginService.loginService(App.userLogin.UserLoginName, App.userLogin.UserPassword);
                    if (result_login.IsSuccess)
                    {
                        if ((String)result_login.ReturnedObject == Constants.SUCCESS)
                        {
                            IsAuthenticated = true;

                            return await RetrieveDeviceLatestMessage(imei);
                        }
                        else
                        {
                            MessageBox.Show((String)result_login.ReturnedObject);
                            App.BackToLoginPage();

                        }
                    }
                    else
                    {
                        MessageBox.Show(result_login.Error);
                        App.BackToLoginPage();

                    }


                }
                #endregion

                result = new InfoResult(null, resultString);
            }
            catch (Exception ex)
            {
                result = new InfoResult(ex.Message, null);
            }
            return result;
        }

        private static MessageModel ParseXML(Stream xmlStream)
        {
            XDocument doc = XDocument.Load(xmlStream);

            var Authenticate = (from authen in doc.Descendants("unauthorized")
                                select new
                                {

                                }).FirstOrDefault();
            if (Authenticate != null)
            {
                IsAuthenticated = false;
                return null;
            }

            var Message = (from message in doc.Descendants("messageDetails")
                           select new
                           {
                               GeneratedAt = message.Element("generatedAt").Value,
                               Heading = message.Element("heading").Value,
                               Ignition = message.Element("ignition").Value,
                               Latitude = message.Element("latitude").Value,
                               Longitude = message.Element("longitude").Value,
                               Odometer = message.Element("odometer").Value,
                               ReceivedAt = message.Element("receivedAt").Value,
                               Speed = message.Element("speed").Value,


                           }).FirstOrDefault();


            if (Message != null)
            {
                MessageModel messageModel = new MessageModel();
                messageModel.GeneratedAt = CommonUtil.ParseDateTimeFromString(Message.GeneratedAt);
                messageModel.Heading = Message.Heading;
                messageModel.Ignition = Message.Ignition;
                messageModel.Latitude = Message.Latitude;
                messageModel.Longitude = Message.Longitude;
                messageModel.Odometer = Message.Odometer;
                messageModel.ReceivedAt = CommonUtil.ParseDateTimeFromString(Message.ReceivedAt);
                messageModel.Speed = Message.Speed;

                return messageModel;
            }

            return null;

        }
    }
}
